package org.putrpctorest.parameter.impl;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;

import org.putrpctorest.parameter.JavaParameterNameDiscover;
import org.putrpctorest.resource.CollectionType;
import org.putrpctorest.resource.Parameter;

public class DefinitionsFactory {

	private static DefinitionsFactory instance = new DefinitionsFactory();

	public static DefinitionsFactory getInstance() {
		return instance;
	}

	private DefinitionsFactory() {

	}

	public Definitions create(Method javaServiceMethod,
			JavaParameterNameDiscover javaParameterNameDiscover) {

		Definitions javaParameters = new Definitions("java");

		Class<?>[] types = javaServiceMethod.getParameterTypes();
		Type[] parameterizedTypes = javaServiceMethod
				.getGenericParameterTypes();
		String[] names = javaParameterNameDiscover
				.getParameterNames(javaServiceMethod);

		CollectionType collectionType;
		Class<?> type;
		for (int i = 0; i < types.length; i++) {
			collectionType = CollectionType.fromType(types[i]);
			type = CollectionType.getTypeFromTypeAndGenericType(types[i],
					parameterizedTypes[i]);

			javaParameters.add(names[i], type, collectionType, "javaParams["
					+ i + "]", null);
		}

		return javaParameters;
	}

	public Definitions create(List<Parameter> restDefinitions) {

		Definitions definitions = new Definitions("rest");

		for (Parameter parameter : restDefinitions) {
			definitions.add(parameter);
		}

		return definitions;
	}

	public Definitions create(List<Definition> parameterDefinitions,
			String description) {

		Definitions definitions = new Definitions(description);
		definitions.addAll(parameterDefinitions);

		return definitions;
	}

}
